<template>
  <!-- 新增编辑的弹层 -->
  <el-dialog
    :visible="showDialog"
    :title="showTitle"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <!-- 表单内容 -->
    <el-form ref="addForm" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
      <el-form-item label="权限启用">
        <el-switch
          v-model="form.enVisible"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="text-align: right">
        <el-button @click="closeDialog">取消</el-button>
        <el-button
          type="primary"
          @click="confirmAddPermission"
        >确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addPermissionApi, getPermissionDetailApi, editPermissionApi } from '@/api/permission'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    type: {
      type: Number,
      required: true
    },
    pid: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '',
        code: '',
        description: '',
        type: 1,
        pid: '',
        enVisible: ''
      },
      rules: {
        name: [
          { required: true, message: '权限名称不可为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不可为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '权限描述不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑权限' : '添加权限'
    }
  },
  methods: {
    /**
     * 回显详情
     */
    async getPermissionDetail(id) {
      const { data } = await getPermissionDetailApi(id)
      this.form = data
    },
    closeDialog() {
      this.$emit('update:showDialog', false)
      this.$refs.addForm.resetFields()
      this.form = {
        name: '',
        code: '',
        description: '',
        type: 1,
        pid: '',
        enVisible: ''
      }
    },
    confirmAddPermission() {
      this.$refs.addForm.validate(async(flag) => {
        if (!flag) return
        if (this.form.id) {
          await editPermissionApi(this.form)
          this.$message.success('编辑成功')
        } else {
          await addPermissionApi({ ...this.form, type: this.type, pid: this.pid })
          this.$message.success('添加成功')
        }
        this.closeDialog()
        this.$parent.getPermissionList()
      })
    }
  }
}
</script>

<style>

</style>
